package com.newhero.product.module.sys.controller;

import com.newhero.product.common.controller.BaseController;
import com.newhero.product.common.mybatis.plugins.Page;
import com.newhero.product.common.mybatis.toolkit.IdWorker;
import com.newhero.product.common.util.GTime;
import com.newhero.product.common.util.StringUtils;
import com.newhero.product.module.sys.model.Attachment;
import com.newhero.product.module.sys.service.IAttachmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by amy on 2018/5/15.
 */
@Controller
@RequestMapping("/admin")
public class AttachmentController extends BaseController {
    @Autowired
    private IAttachmentService attachmentServiceImpl;

    /**
     * 附件列表页面（分页）
     * @param page 页号
     * @param rows 每页显示的记录条数
     * @param sourceId 附件所属资源id
     * @param model model
     * @return
     */
    @RequestMapping(value = "/attachmentPageList", method = { RequestMethod.GET, RequestMethod.POST })
    public String attachmentPageList(@RequestParam(value = "page", defaultValue = "1", required = true) int page,
                                 @RequestParam(value = "rows", defaultValue = "" + _ROWS_PER_PAGE, required = true) int rows,
                                 @RequestParam(value = "sourceId", required = false) String sourceId,
                                 ModelMap model) {
        Page<Attachment> p = new Page<Attachment>();
        p.setCurrent(page);
        p.setSize(rows);
        if (StringUtils.isNotBlank(sourceId)) {
            attachmentServiceImpl.selectAttachmentsBySourceId(p, sourceId);
            model.addAttribute("sourceId", sourceId);
        }
        model.addAttribute("data", p);
        return "sys/attachment/attachmentPageList";
    }

    /**
     * 附件列表页面（不分页）
     *
     * @param sourceId 附件所属资源id
     * @param model    model
     * @return
     */
    @RequestMapping(value = "/attachmentList", method = {RequestMethod.GET})
    public String attachmentList(@RequestParam(value = "sourceId", required = false) String sourceId, ModelMap model) {
        if (StringUtils.isNotBlank(sourceId)) {
            List<Attachment> attachments = attachmentServiceImpl.selectAttachmentsBySourceId(sourceId);
            model.addAttribute("attachments", attachments);
            model.addAttribute("sourceId", sourceId);
        }
        return "sys/attachment/attachmentList";
    }

    /**
     * 附件表单
     *
     * @param sourceId 附件所属资源id
     * @param request
     * @return
     */
    @RequestMapping(value = "/attachmentForm", method = {RequestMethod.GET, RequestMethod.POST})
    public String attachmentForm(String sourceId, HttpServletRequest request) {
        request.setAttribute("id", "");
        request.setAttribute("sourceId", sourceId);
        return "/sys/attachment/attachmentForm";
    }

    /**
     * 附件上传
     * @param attachment 附件对象详细信息
     * @param file  上传文件信息
     * @param request
     * @param response
     * @param model
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/uploadAttachment", method ={RequestMethod.GET,RequestMethod.POST })
    public Map<String, Object> uploadAttachment(Attachment attachment,
                                          @RequestParam(value = "file", required = true) MultipartFile file,
                                          HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String fileID = IdWorker.getId();
        String originalFileName = file.getOriginalFilename();
        String ext = originalFileName.substring(originalFileName.lastIndexOf("."));
        String filePath = getConfig("uploadFilePath");
        if("".equals(filePath)){
            filePath = request.getSession().getServletContext().getRealPath("/").replace("\\", "/");
        }
        filePath +=  "/attachment" + "/" + GTime.getTime(GTime.YYYYMM)+ "/" + attachment.getSourceId() ;
        File baseFolder = new File(filePath);
        if(!baseFolder.exists()){
            baseFolder.mkdirs();
        }
        filePath += "/" + fileID  + ext;
        try {
            file.transferTo(new File(filePath));
            attachment.setAttachmentSize((int)file.getSize());
            attachment.setAttachmentSuffix(ext.substring(1));
            attachment.setAttachmentPath(filePath);
            attachment.setAttachmentUptime(GTime.getNormalTime());
            attachment.setAttachmentUserId(this.getUserID());
            attachment.setAttachmentUserName(this.getUserName());
            attachmentServiceImpl.insert(attachment);
        } catch (IOException e) {
            e.printStackTrace();
        }
        resultMap.put("success", true);
        return resultMap;
    }

    /**
     * 附件下载
     * @param attachmentId 附件主键id
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/downLoadAttachment", method = { RequestMethod.GET, RequestMethod.POST })
    public void downLoadAttachment(@RequestParam(value = "attachmentId", required = true) String attachmentId,
                         HttpServletRequest request,HttpServletResponse response) throws IOException {
        Attachment attachment = attachmentServiceImpl.selectById(attachmentId);
        String attachmentPath = attachment.getAttachmentPath();
        File outfile = new File(attachmentPath);
        String filename = outfile.getName();// 获取文件名称
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        response.setHeader("Content-Disposition", "attachment; " + "filename="
                + new String(filename.getBytes("gb2312"), "iso8859-1"));
        bis = new BufferedInputStream(new FileInputStream(attachmentPath));
        bos = new BufferedOutputStream(response.getOutputStream());
        byte[] buff = new byte[2048];
        int bytesRead;
        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
            bos.write(buff, 0, bytesRead);
        }
        bis.close();
        bos.close();
    }
    /**
     * 附件删除
     * @param attachmentId 附件主键id
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/deleteAttachment", method ={RequestMethod.GET,RequestMethod.POST })
    public Map<String, Object> deleteAttachment(@RequestParam(value = "attachmentId", required = true) String attachmentId,
                                                HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Attachment attachment = attachmentServiceImpl.selectById(attachmentId);
        File file = new File(attachment.getAttachmentPath());
        if (!file.exists()) {
            System.out.println("删除文件失败:" + attachment.getAttachmentName() + "不存在！");
        } else {
            if (file.isFile()) {
                if(!file.delete()){
                    System.out.println("删除文件失败！");
                }
            }
        }
        attachmentServiceImpl.deleteById(attachmentId);
        resultMap.put("success", true);
        return resultMap;
    }
}
